package controllers

import (
	"fmt"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/http/requests"
	"goravel/app/models"
	"goravel/app/services/kind"
)

type KindController struct {
	//Dependent services
	kind.KindService
}

func NewKindController() *KindController {
	return &KindController{
		//Inject services
	}
}

// List
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindList
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/kind/list [get]
func (r *KindController) List(ctx http.Context) http.Response {
	kinds := []models.Kind{}

	facades.Orm().Query().Model(&models.Kind{}).Find(&kinds)
	return httpfacade.NewResult(ctx).Success("", kinds)
}

// Tree 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindTree
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/kind/tree [get]
func (r *KindController) Tree(ctx http.Context) http.Response {

	tree, err := r.RecursionGet()
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, err.Error(), nil)
	}
	return httpfacade.NewResult(ctx).Success("", tree)
}

// Option  后代
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindOption
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param kindData body interface{}  true "关键词"
// @Success 200 {string} json {}
// @Router       /api/admin/kind/option [post]
func (r *KindController) Option(ctx http.Context) http.Response {
	name := ctx.Request().Input("name")
	kinds := []models.Kind{}
	execSql := fmt.Sprintf(`
        SELECT k.*
        FROM kinds k
        LEFT JOIN kinds sub_kinds ON k.id = sub_kinds.pid
        WHERE sub_kinds.id IS NULL and k.deleted_at is null
        AND k.name LIKE '%s';
    `, fmt.Sprintf("%%%s%%", name))

	facades.Orm().Query().Raw(execSql).Scan(&kinds)
	return httpfacade.NewResult(ctx).Success("", kinds)
}

// Store
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindStore
// @Security ApiKeyAuth
// @Param userData body requests.KindRequest true "用户数据"
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/kind [post]
func (r *KindController) Store(ctx http.Context) http.Response {
	var kindRequest requests.KindRequest
	errors, err := ctx.Request().ValidateRequest(&kindRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	facades.Orm().Query().Model(&models.Kind{}).Create(&models.Kind{
		Name: kindRequest.Name,
		Pid:  kindRequest.Pid,
	})
	return httpfacade.NewResult(ctx).Success("创建成功", nil)
}

// Update
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindUpdate
// @Security ApiKeyAuth
// @Param userData body requests.KindRequest true "用户数据"
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/kind/{id} [put]
func (r *KindController) Update(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	kind := models.Kind{}
	facades.Orm().Query().Model(&models.Kind{}).Where("id=?", id).Find(&kind)
	var kindRequest requests.KindRequest
	errors, err := ctx.Request().ValidateRequest(&kindRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	kind.Name = kindRequest.Name
	kind.Pid = kindRequest.Pid
	facades.Orm().Query().Model(&models.Kind{}).Where("id=?", id).Save(&kind)
	return httpfacade.NewResult(ctx).Success("修改成功", nil)
}

// Destroy
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         KindController
// @Accept       json
// @Produce      json
// @Id KindDestroy
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/kind/{id} [delete]
func (r *KindController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	kind := models.Kind{}
	facades.Orm().Query().Model(&models.Kind{}).Where("id=?", id).Delete(&kind, id)
	return httpfacade.NewResult(ctx).Success("删除成功", nil)
}
